package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.PetDao;
import dao.PetDaoImpl;
import entity.Pet;

@WebServlet(urlPatterns = "/addPet")
public class AddPetServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private PetDao petDao;

    public AddPetServlet() {
        super();
        petDao = new PetDaoImpl();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String petName = request.getParameter("petName");
        int petBreed = Integer.parseInt(request.getParameter("petBreed"));
        int petSex = Integer.parseInt(request.getParameter("petSex"));
        String birthdayStr = request.getParameter("birthday");
        String description = request.getParameter("description");

        // 将生日字符串转换为 Date 对象
        java.util.Date birthday = null;
        try {
            birthday = new java.text.SimpleDateFormat("yyyy-MM-dd").parse(birthdayStr);
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }

        // 创建 Pet 对象
        Pet pet = new Pet();
        pet.setPetName(petName);
        pet.setPetBreed(petBreed);
        pet.setPetSex(petSex);
        pet.setBirthday(birthday);
        pet.setDescription(description);

        // 检查宠物名称是否唯一
        if (!petDao.isPetNameUnique(petName)) {
            request.setAttribute("error", "宠物名称已存在，请选择其他名称！");
            request.getRequestDispatcher("/addPet.jsp").forward(request, response);
            return;
        }

        // 添加宠物
        petDao.addPet(pet);

        // 重定向到宠物列表页面
        response.sendRedirect(request.getContextPath() + "/listPets");
    }
}
